package com.lancoo.answer.util;

import android.content.Context;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.lancoo.answer.util.encodeUtils.EncodingUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WebStyleUtils {

    //点击事件
    public static String Function_click =
            "    <script type=\"text/javascript\">" +
                    "    function CalledByJavaCodeWithPara(id,arg) {" +
                    "         document.getElementById(id).innerHTML = arg;" +
                    "      }" +
                    "    </script>";

    //点击背景高亮
    public static String Function_backgroundColor =
            "    <script type=\"text/javascript\">" +
                    "    function setBackGroundColor(id,bgColor,Radius,BottomH) {" +
                    "         document.getElementById(id).style.backgroundColor = bgColor;" +
                    "         document.getElementById(id).style.borderRadius = Radius;" +
                    "         document.getElementById(id).style.borderBottom = BottomH;" +
                    "      }" +
                    "    </script>";

    //用于篇章翻译
    public static String Function_textColor =
            "    <script type=\"text/javascript\">" +
                    "  function setTextColor(id, textColor) {" +
                    "         document.getElementById(id).style.color = textColor;" +
                    "      }" +
                    "    </script>";


    public static String Function_showAnalysisWithId =
            "    <script type=\"text/javascript\">" +
                    "    function showAnalysisWithId(id) { " +
                    "  var analysisList = document.getElementsByClassName('itemAnalysis');" +
                    "   for(var i=0;i < analysisList.length; i++) {" +
                    "  var analysis = analysisList[i];" +
                    "   analysis.style.display = 'none'; " +
                    "  }" +
                    "  var analysis = document.getElementById(id);" +
                    "  analysis.style.display = 'block'; " +
                    "  } " +
                    "    </script>";

    public static String Function_showFlagWithId =
            "    <script type=\"text/javascript\">" +
                    " function showFlagWithId(id, isShow,url) { " +
                    "  var flag = document.getElementById(id);" +
                    "  if(isShow == 1) {" +
                    "    flag.style.display = 'inline-block'; " +
                    "    flag.style.backgroundColor = '#ff0000'; " +
                    "    flag.style.height = '14px'; " +
                    "    flag.style.width = '17px'; " +
                    "    flag.style.background = 'url('+url+')'; " +
                    "    flag.style.backgroundSize = '14px 14px'; " +
                    "    flag.style.backgroundPosition = 'left'; " +
                    "    flag.style.backgroundRepeat = 'no-repeat'; " +
                    "   }else{" +
                    "        flag.style.display = 'none'; " +
                    "    }" +
                    "  } " +
                    "    </script>";

    //填空题 [析]
    public static String Function_showOrHideAnalysisButton =
            "    <script type=\"text/javascript\">" +
                    "     function showOrHideAnalysisButton(isShow) {" +
                    "      var analysisList = document.getElementsByClassName('znbkanalysis');" +
                    "      for(var i=0;i < analysisList.length; i++) {" +
                    "      var analysis = analysisList[i];" +
                    "       if(isShow == 1){" +
                    "       analysis.style.display = 'inline'; " +
                    "        }else{" +
                    "       analysis.style.display = 'none'; " +
                    "           }" +
                    "        }" +
                    "       } " +
                    "    </script>";

    public static String Function_showOrHideClauseIndex =
            "    <script type=\"text/javascript\">" +
                    "     function showOrHideClauseIndex(isShow) {" +
                    "      var analysisList = document.getElementsByClassName('znbk-clauseindex');" +
                    "      for(var i=0;i < analysisList.length; i++) {" +
                    "      var analysis = analysisList[i];" +
                    "       if(isShow == 1){" +
                    "       analysis.style.display = 'inline'; " +
                    "        }else{" +
                    "       analysis.style.display = 'none'; " +
                    "           }" +
                    "        }" +
                    "       } " +
                    "    </script>";

    //当前焦点离顶部的距离
    public static String Function_topHeight =
            "    <script type=\"text/javascript\">" +
                    "  function topHeight(id) {" +
                    "    var input = document.getElementById(id);" +
                    "   　var actualTop = input.offsetTop;" +
                    "　　　　var current = input.offsetParent;" +
                    "　　　　while (current !== null){" +
                    "　　　　　　actualTop += current. offsetTop;" +
                    "　　　　　　current = current.offsetParent;" +
                    "　　　　}" +
                    "　　　　return actualTop;" +
                    "      }" +
                    "    </script>";


    public static String WebString = "<style type=\"text/css\"> \n" +
            "body {text-align:justify; font-size: " + 16 + "px!important; " +
            "line-height: " + (16 + 10) + "px!important;" +
            "color:#666666!important;" +
            "\"font-family:'PingFangSC-Regular','Arial','Times New Roman', 'SimSun' !important\"}\n" +
            "p{margin: " + (5) + "px 0}" +
            "</style> \n";

    public static String getWebString(String strAsk) {
        String strWebString = EncodingUtils.getString(strAsk.getBytes(), "UTF-8");
        return strWebString;
    }

    /**
     * 设置网页中图片的点击事件
     *
     * @param view
     */
    public static void setWebImageClick(WebView view, String method) {
        String jsCode = "javascript:(function(){" +
                "var imgs=document.getElementsByTagName(\"img\");" +
                "for(var i=0;i<imgs.length;i++){" +
                "imgs[i].pos = i;" +
                "imgs[i].onclick=function(){" +
                "window." + method + ".openImage(this.src,this.pos);" +
                "}}})()";
        view.loadUrl(jsCode);
    }

    //获取webview 中的 ImageUrl
    public static String[] returnImageUrlsFromHtml(String htmlCode) {
        List<String> imageSrcList = new ArrayList<>();
        Pattern p = Pattern.compile("<(?i)img\\b[^>]*\\bsrc\\b\\s*=\\s*('|\")?([^'\"\n\r\f>]+(\\.jpg|\\.bmp|\\.eps|\\.gif|\\.mif|\\.miff|\\.png|\\.tif|\\.tiff|\\.svg|\\.wmf|\\.jpe|\\.jpeg|\\.dib|\\.ico|\\.tga|\\.cut|\\.pic|\\b)\\b)[^>]*>", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(htmlCode);
        String quote;
        String src;
        while (m.find()) {
            quote = m.group(1);
            src = (quote == null || quote.trim().length() == 0) ? m.group(2).split("//s+")[0] : m.group(2);
            imageSrcList.add(src);
        }
        if (imageSrcList.size() == 0) {
            return null;
        }
        return imageSrcList.toArray(new String[imageSrcList.size()]);
    }

    public static void initWebView(Context context, WebView wv) {
        WebSettings settings = wv.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);//是否开启本地DOM存储
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
    }

    //展示题干 isIndentation 比如单选题就不缩进
    public static void showWebViewCssStyle(Context context,
                                           WebView wv,
                                           String strAsk,
                                           Boolean indentation,
                                           Boolean isKlg) {
        strAsk = strAsk.replace("clickFunction", "Android.clickFunction");
        boolean isIndentation = indentation && !strAsk.contains("<TABLE");
        //长按事件
        wv.setOnLongClickListener(v -> true);
        // 先把所有的style干掉 - 正则表达式(反向替换)
        strAsk = strAsk.replaceAll("(<span.*?)style=\".*?\"", "$1");
        //没办法的办法(适配TD标签的style)
        String regEx_TD_PaddingTop = "PADDING-TOP: 0cm;";
        strAsk = strAsk.replaceAll(regEx_TD_PaddingTop, "PADDING-TOP: 5.4pt;");
        String regEx_TD_PaddingBottom = "PADDING-BOTTOM: 0cm;";
        strAsk = strAsk.replaceAll(regEx_TD_PaddingBottom, "PADDING-BOTTOM: 5.4pt;");

        initWebView(context, wv);
        //todo 部分图片显示异常，处理方式待定
//        strAsk = strAsk.replaceAll("(?i)<img", "<img style=max-width:90%;height:auto");
        strAsk = strAsk.replaceAll("(?i)<img", "<img style=max-width:100%;height:auto");

        //最新屏蔽，适配平板横屏显示（手机需要开放）
        String newTableStyle = "<TABLE style=\"text-align:left;\"vertical-align:left;\"table-layout: fixed;\"" +
                " border=\"1\" width=\"100%\" cellspacing=\"0\" cellpadding=\"10\">";
        ArrayList<String> arrayStrList = getAllSatisfyStr(strAsk, "<TABLE(.*?)>");

        if (arrayStrList != null) {
            for (int i = 0; i < arrayStrList.size(); i++) {
                strAsk = strAsk.replaceAll(arrayStrList.get(i), newTableStyle);
            }
        }
        getWebContent(wv, strAsk + "<br>", isIndentation, isKlg);
    }

    /**
     * 修改webview样式(assets--css文件)
     *
     * @param webview
     * @param ask
     */
    public static void getWebContent(WebView webview, String ask, boolean isIndentation, boolean isKlg) {

        webview.setBackgroundColor(0);
        webview.getBackground().setAlpha(2);
        webview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        String linkCss = "";
        if (isIndentation) {
            linkCss = "<link rel=\"stylesheet\" href=\"file:///android_asset/NewCssStyle.css\" type=\"text/css\">";
        } else {
            linkCss = "<link rel=\"stylesheet\" href=\"file:///android_asset/CssStyle.css\" type=\"text/css\">";
        }

        Document document = Jsoup.parse(ask);
        document.head().append(linkCss);
        document.head().append(Function_click);
        document.head().append(Function_backgroundColor);
        document.head().append(Function_textColor);
        document.head().append(Function_showAnalysisWithId);
        document.head().append(Function_showFlagWithId);

        document.head().append(Function_showOrHideAnalysisButton);
        document.head().append(Function_showOrHideClauseIndex);
        document.head().append(Function_topHeight);
        if (isKlg) {
            document.head().append("<script type=\"text/javascript\" src=\"file:///android_asset/js/jquery_1.12.4.min.js\"></script>");
            document.head().append("<script type=\"text/javascript\" src=\"file:///android_asset/js/content.js\"></script>");
            document.head().append("<script type=\"text/javascript\" src=\"file:///android_asset/js/MarkKlg.js\"></script>");
        }
        document.head().append(WebString);
        webview.loadDataWithBaseURL(null, document.outerHtml(), "text/html", "UTF-8", null);
    }

    /**
     * 获取所有满足正则表达式的字符串
     *
     * @param str   需要被获取的字符串
     * @param regex 正则表达式
     * @return 所有满足正则表达式的字符串
     */
    public static ArrayList<String> getAllSatisfyStr(String str, String regex) {
        if (str == null || str.isEmpty()) {
            return null;
        }
        ArrayList<String> allSatisfyStr = new ArrayList<>();
        if (regex == null || regex.isEmpty()) {
            allSatisfyStr.add(str);
            return allSatisfyStr;
        }
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            allSatisfyStr.add(matcher.group());
        }
        return allSatisfyStr;
    }

}